﻿namespace ITSSP.Web.Models
{
    using System;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Security.Cryptography;
    using System.Text;

    public partial class User
    {
        #region 'Synching' Hashed and Clear-Text passwords
        partial void OnPasswordConfirmationChanged()
        {
            if (this.Password == null) return;

            if (this.Password.Length == 0)
            {
                // clear password
                this.HashedPassword = null;
            }
            else
            {
				this.HashedPassword = generateNewPasswordHash(this.Password);
            }
        }
        #endregion

        #region Password Field
        [Display(Order = 6, Name = "Password", AutoGenerateField = false, AutoGenerateFilter = false)]
        public string Password
        {
            get { return this._password; }
            set
            {
                OnPasswordChanging(value);
                this.ValidateProperty("Password", value);
                this._password = value;
                this.RaisePropertyChanged("Password");
                OnPasswordChanged();
            }
        }
        private string _password;
        partial void OnPasswordChanging(String value);
        partial void OnPasswordChanged();
        #endregion

        #region Password Confirmation Field
        [Display(Order = 7, Name = "Password Confirmation", AutoGenerateField = false, AutoGenerateFilter = false)]        
        [CustomValidation(typeof(User), "CheckPasswordConfirmation")]
        public string PasswordConfirmation
        {
            get { return this._passwordConfirmation; }
            set
            {
                OnPasswordConfirmationChanging(value);
                this.ValidateProperty("PasswordConfirmation", value);
                this._passwordConfirmation = value;
                this.RaisePropertyChanged("PasswordConfirmation");
                OnPasswordConfirmationChanged();
            }
        }
        private string _passwordConfirmation;
        partial void OnPasswordConfirmationChanging(String value);
        partial void OnPasswordConfirmationChanged();
        #endregion

        #region Validations
        public static ValidationResult CheckPasswordConfirmation(string passwordConfirmation, ValidationContext validationContext)
        {
            User user = (User)validationContext.ObjectInstance;

            if ((user.Password == passwordConfirmation) || (Convert.ToString(user.Password) == passwordConfirmation))
            {
                return ValidationResult.Success;
            }

            return new ValidationResult("Password confirmation did not match.");
        }
        #endregion
    }
}